package com.comtime.smartbox;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.comtime.greendaodemo.DeviceInfo;
import com.comtime.greendaoutils.DataBaseUtil;
import com.comtime.service.MyService;
import com.comtime.smartkilimanjaro.R;
import com.comtime.swdevice.DeviceScanCallBack;
import com.comtime.swdevice.SWDeviceScanManager;
import com.comtime.utils.LogUtils;
import com.comtime.utils.MD5Util;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.ToastUtils;
import com.comtime.view.MyDialog;
import com.comtime.view.SpringProgressView;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Activity_0 extends BaseActivity implements OnClickListener {

	HBApplication application;
	
	public final static String Extra_RemoveScan=Activity_0.class.getName()+ ".removeScan";

	List<BluetoothDevice> devicelist = new ArrayList<BluetoothDevice>();

	SWDeviceScanManager scanManager;

	RelativeLayout line_one;// 搜索箱子外框
	LinearLayout line_name;// 箱子名字
	ImageView image_round, image_search, image_bag;
	TextView tv_content_center, tv_content_button;

	LinearLayout relate_open;// 蓝牙开关
	
	LinearLayout relate_not_found;// 
	
	RelativeLayout relate_search;//

	// 按箱子解锁
	LinearLayout line_top;

	// 设备名字显示
	RelativeLayout relate_top;
	TextView tv_name;// 设备名字显示

	// 电量显示
	RelativeLayout relate_progress;
	ProgressBar progressBar;
	TextView tv_progress;// 进度

	DataBaseUtil dataBaseUtil;
	
	
	LinearLayout line_test;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_0);
		application = (HBApplication) getApplication();
		dataBaseUtil = DataBaseUtil.getInstance(this);
		init();
		register();
		addListMySharedPreferences();
		line_test=(LinearLayout) findViewById(R.id.line_test);
	}

	
	public void buttonAction_1(View v){
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		//httpProgram.add("phoneNum", mySharedPreferences.getPhoneNum());
		httpProgram.add("user_id", mySharedPreferences.getUserId()+"");

		String address=mySharedPreferences.getBluAdress();
		httpProgram.add("mac", address);
		httpProgram.add("describe", "大拇指");
		httpProgram.add("zw_device_id", "1");
		// httpProgram:{zw_device_id=1, user_id=3, describe=大拇指, mac=987BF36134E3}
		LogUtils.e("tag", " httpProgram:"+httpProgram.getPrograms().toString());
		
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "app/Login/zw_add");
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

			@Override
			public void onResponse(final String string) {
				Log.e("tag", "1 bind_success=============" + string);
				
//				handler.post(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//						ToastUtils.showToast(MyService.this, "1 bind_success=============" + string, 3000);
//					}
//				});
				
			 
				try {
					JSONObject jsonObject = new JSONObject(string);
					int err = jsonObject.getInt("err");
					if (err == 0) {
//						JSONObject dataObject = jsonObject
//								.getJSONObject("data");
						
						
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(String arg0, IOException arg1) {
				// TODO Auto-generated method stub
				 LogUtils.e("tag", "  bindDevice 44444"+arg1  );
			}
		});
	}
	public void buttonAction_2(View v){
		 application.swDevicesList.get(0).sendUnlockRecordQuery();
	}
	public void buttonAction_3(View v){
		 application.swDevicesList.get(0).sendRegisterlock();
	}
	public void buttonAction_4(View v){
		application.swDevicesList.get(0).sendLockStateQuery();
	}
	
	private void init() {

		line_top = (LinearLayout) findViewById(R.id.line_top);

		relate_top = (RelativeLayout) findViewById(R.id.relate_top);
		line_name = (LinearLayout) findViewById(R.id.line_name);

		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_content_center = (TextView) findViewById(R.id.tv_content_center);
		tv_content_button = (TextView) findViewById(R.id.tv_content_button);

		line_one = (RelativeLayout) findViewById(R.id.line_one);

		image_search = (ImageView) findViewById(R.id.image_search);
		image_round = (ImageView) findViewById(R.id.image_round);
		image_round.setOnClickListener(this);

		image_bag = (ImageView) findViewById(R.id.image_bag);
		image_bag.setOnClickListener(this);

		image_bag.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View arg0) {
				 
				if(application.swDevicesList.get(0).isConnected()){
					//TODO:解锁成功，应该上传解锁记录
					application.swDevicesList.get(0).sendUnlock(303);

					
				}
				return false;
			}
		});
		
		relate_search = (RelativeLayout) findViewById(R.id.relate_search);

		relate_open = (LinearLayout) findViewById(R.id.relate_open);
		relate_open.setOnClickListener(this);
		
		relate_not_found = (LinearLayout) findViewById(R.id.relate_not_found);

		relate_progress = (RelativeLayout) findViewById(R.id.relate_progress);
		progressBar = (ProgressBar) findViewById(R.id.progressbar);

		tv_progress = (TextView) findViewById(R.id.tv_progress);
		if (MyConfig.bluetoothEnabled) {
			relate_open.setVisibility(View.INVISIBLE);

		} else {
			relate_open.setVisibility(View.VISIBLE);
		}
		
		relate_not_found.setVisibility(View.INVISIBLE);
	}

	/**
	 * 配置文件
	 */
	MySharedPreferences mySharedPreferences;

	void addListMySharedPreferences() {
		mySharedPreferences = MySharedPreferences.getInstance(this);
	}

	IntentFilter filter;

	void register() {
		filter = new IntentFilter(MyService.ACTION_UPDATE_UI);
		filter.addAction(MyService.ACTION_CONNECTED);
		filter.addAction(MyService.ACTION_DISCONNECTED);
		filter.addAction(MyService.ACTION_BLUTOOTH_CHANGE);
		filter.addAction(MyService.ACTION_HOME_UI_CHANGE);
		registerReceiver(receiver, filter);
	}

	String action = "";
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			action = intent.getAction();
			if (action.equals(MyService.ACTION_UPDATE_UI)) {
				Log.e("tag",
						"ACTION_UPDATE_UI:"
								+ mySharedPreferences.getBluAdress());
				updateUI();
				boolean removeScan=intent.getBooleanExtra(Extra_RemoveScan, false);
				if(removeScan){
					handler.removeCallbacks(scanResultRunnable);
				}
			} else if (action.equals(MyService.ACTION_CONNECTED)) {

				updateUI();

			} else if (action.equals(MyService.ACTION_DISCONNECTED)) {
				handler.removeCallbacks(batteryRunnable);
				updateUI();
			} else if (action.equals(MyService.ACTION_BATTERYVALUE)) {
				
				showProgress(application.swDevicesList.get(0).battery);

			} else if (action.equals(MyService.ACTION_BLUTOOTH_CHANGE)) {

				if (MyConfig.bluetoothEnabled) {
					relate_open.setVisibility(View.INVISIBLE);

				} else {
					relate_open.setVisibility(View.VISIBLE);
				}
			} else if (action.equals(MyService.ACTION_HOME_UI_CHANGE)) {
				updateUI();
			}

		}
	};

	private void updateUI() {

		if (mySharedPreferences.getBluAdress().equals("")) {
			// 没有设备
			line_name.setVisibility(View.INVISIBLE);
			line_one.setVisibility(View.VISIBLE);
			relate_search.setVisibility(View.VISIBLE);
			image_round.setVisibility(View.VISIBLE);
			tv_content_center.setText(R.string.add_device);
			image_search.setVisibility(View.INVISIBLE);
			image_bag.setVisibility(View.INVISIBLE);
			
			
			line_test.setVisibility(View.INVISIBLE);
			relate_top.setVisibility(View.INVISIBLE);
			line_top.setVisibility(View.INVISIBLE);
		} else {
			// 有设备
			line_one.setVisibility(View.GONE);
			boolean isConnected = application.swDevicesList.get(0)
					.isConnected();
			relate_search.setVisibility(View.INVISIBLE);
			image_bag.setVisibility(View.VISIBLE);
			
			if(MyConfig.Test_ZhiWen){
				line_test.setVisibility(View.VISIBLE);
			}
		
			if (isConnected) {
				image_bag.setImageResource(R.drawable.icon_home_bag_off);
			} else {
				image_bag.setImageResource(R.drawable.icon_home_bag_nocon);
			}

			relate_top.setVisibility(View.VISIBLE);
			line_name.setVisibility(View.VISIBLE);
			relate_progress.setVisibility(View.GONE);
			tv_name.setText(mySharedPreferences.getBluAdress());

			line_top.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 设置进度条
	 */
	void showProgress(int battery){
//		battery=50;
		progressBar.setProgress(battery);
		tv_progress.setText(battery+"%");
		Drawable drawable=null;
		if(battery<=10){
			drawable=getResources().getDrawable(R.drawable.progress_horizontal_red);
		}else if(battery>10&&battery<60){
			drawable=getResources().getDrawable(R.drawable.progress_horizontal_yellow);
		}else{
			drawable=getResources().getDrawable(R.drawable.progress_horizontal_green);
		}
		progressBar.setProgressDrawable(drawable);
	}
	
	/**
	 * 自定义提示语
	 * 
	 * @param str
	 */
	Toast toast = null;

	void showToast(String str) {
		if (toast != null) {
			toast.cancel();
		} else {
			toast = new Toast(this);
		}
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.toastshow, null);
		TextView textView = (TextView) view.findViewById(R.id.toastshow);
		textView.setText(str);

		double d = getResources().getDisplayMetrics().density;
		toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(view);
		toast.show();
	}

	void showSuccessDialog(String str) {
		final MyDialog myDialog = new MyDialog(Activity_0.this);
		myDialog.setContent(str);
		myDialog.getLeftButton().setText(getText(R.string.ok));
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				myDialog.dismiss();

			}
		});
		myDialog.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.image_round:

			if (!MyConfig.canUse) {

				showCanUseDialog(getText(R.string.unsupport_ble).toString());
				//不支持蓝牙功能应该直接退出程序
				//应该在用户进入APP的时候就给出判断不支持就退出程序
				//TODO
			}

			BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
					.getDefaultAdapter();


			if (!mBluetoothAdapter.isEnabled()) {

				showSetBloothDialog(getText(R.string.blooth_open_content).toString());

				return;
			}

			image_search.setVisibility(View.VISIBLE);

			rotate(image_search);
			if (scanManager == null) {
				scanManager = new SWDeviceScanManager(Activity_0.this);
				scanManager.setScanCallBack(callBack);
			}
			if (devicelist != null) {
				devicelist.clear();
			}
			tv_content_center.setText(getText(R.string.search_box));
			
			relate_not_found.setVisibility(View.INVISIBLE);
			
			image_round.setEnabled(false);
			scanManager.startScan();
			handler.postDelayed(scanResultRunnable, 5 * 1000);
			break;

		case R.id.relate_open:
			// 打开蓝牙

			showSetBloothDialog(getText(R.string.blooth_open_content)
					.toString());

			break;
		case R.id.image_bag:
			// 显示电量
			if (!MyConfig.canUse) {

				showCanUseDialog(getText(R.string.unsupport_ble).toString());
			}
			if (!application.swDevicesList.get(0).isConnected()) {
				showCanUseDialog(getText(R.string.device_dis_connect)
						.toString());
			} else {
				line_name.setVisibility(View.GONE);
				relate_progress.setVisibility(View.VISIBLE);
				showProgress(application.swDevicesList.get(0).battery);
				handler.removeCallbacks(batteryRunnable);
				handler.postDelayed(batteryRunnable, 3000);

			}
			//让设备报警
			//application.swDevicesList.get(0).startRing();
			break;

		default:
			break;
		}
	}

	
	private Runnable scanResultRunnable=new Runnable() {
		
		@Override
		public void run() {
			image_round.setEnabled(true);
			stopRotate(image_search);
			scanManager.stopScan();

			if (devicelist != null && devicelist.size() == 1) {
				
				
				
				application.swDevicesList.get(0).setBluetoothDevice(
						devicelist.get(0));
				application.swDevicesList.get(0).connectGatt();
				mySharedPreferences.saveBluAdress(devicelist.get(0)
						.getAddress().replace(":", "").toUpperCase());
				Intent intent = new Intent(MyService.ACTION_MYSERVICE);
				intent.putExtra(MyService.VALUE_TAG, 1);
				sendBroadcast(intent);

				devicelist.clear();
				line_one.setVisibility(View.INVISIBLE);
				image_bag.setVisibility(View.VISIBLE);
				if(MyConfig.Test_ZhiWen){
					line_test.setVisibility(View.VISIBLE);
				}
			} else {
				line_one.setVisibility(View.VISIBLE);
				relate_search.setVisibility(View.VISIBLE);

				image_search.setVisibility(View.INVISIBLE);
				tv_content_center
						.setText(getText(R.string.reset_add_box));
				
				relate_not_found.setVisibility(View.VISIBLE);
				
				// tv_content_button.setVisibility(View.VISIBLE);
			}
			
		}
	};
	
	
	
	private DeviceScanCallBack callBack = new DeviceScanCallBack() {
		@Override
		
		public void onLeScan(BluetoothDevice device, int rssi, byte[] arg2) {
			Log.e("tag",
					"onLeScan 2 " + device.getAddress() + " name:"
							+ device.getName() +" rssi:"+rssi);
			if (rssi > -70 && !devicelist.contains(device)&&device.getName()!=null&&!device.getName().equals("")
					&& device.getName().contains("Kilimanjaro")) {
				devicelist.add(device);
			}
		}
	};

	Handler handler = new Handler();

	Runnable batteryRunnable = new Runnable() {

		@Override
		public void run() {

			line_name.setVisibility(View.VISIBLE);
			relate_progress.setVisibility(View.GONE);
		}
	};

	Animation anim, arrowAnimation, searchAnim, rightLeftAnim;

	/**
	 * 转圈圈
	 */
	private void rotate(ImageView image_light) {
		image_light.clearAnimation();
		image_light.setVisibility(View.VISIBLE);
		if (anim == null) {
			anim = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF,
					0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
			anim.setRepeatCount(Animation.INFINITE);
			anim.setDuration(2000);
			anim.setInterpolator(new LinearInterpolator());
		}
		image_light.startAnimation(anim);

	}

	private void stopRotate(ImageView image_light) {
		image_light.clearAnimation();
		image_light.setVisibility(View.INVISIBLE);
	}

	public void onResume() {

		super.onResume();
		if (MyConfig.canUse) {
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {
					updateUI();
				}
			}, 200);

		}
	};

	/**
	 * 蓝牙打开
	 * 
	 * @param str
	 */
	void showSetBloothDialog(String str) {
		final MyDialog myDialog = new MyDialog(Activity_0.this);
		myDialog.setContent(str);
		myDialog.getLeftButton().setText(getText(R.string.setting));
		myDialog.getRighrButton().setText(getText(R.string.good));
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();
				startActivity(new

				Intent(Settings.ACTION_BLUETOOTH_SETTINGS));// 直接进入手机中的蓝牙设置界面

			}
		});
		myDialog.getRighrButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();

			}
		});
		myDialog.show();
	}

	/**
	 * 不支持4.3以下
	 * 
	 * @param str
	 */
	void showCanUseDialog(String str) {
		final MyDialog myDialog = new MyDialog(Activity_0.this);
		myDialog.setContent(str);
		myDialog.getLeftButton().setText(getText(R.string.ok));
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();

			}
		});

		myDialog.show();
	}

	/***************************** 绑定设备 **************************************/
	void binddevice(final String mac) {
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		httpProgram.add("phoneNum", mySharedPreferences.getPhoneNum());
		httpProgram.add("mac", mac);
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "login.php");
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

			@Override
			public void onResponse(String resString) {
				try {
					JSONObject jsonObject = new JSONObject(resString);
					int err = jsonObject.getInt("err");
					if (err == 0) {
						JSONObject dataObject = jsonObject
								.getJSONObject("data");
						int device_id = dataObject.getInt("device_id");
						DeviceInfo deviceInfo = new DeviceInfo();
						deviceInfo.setMac(mac);
						dataBaseUtil.saveDeviceInfo(deviceInfo);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(String arg0, IOException arg1) {
				// TODO Auto-generated method stub

			}
		});
	}

	

}
